%%%-------------------------------------------------------------------
%%% @author liuwentao
%%% @doc
%%%     角色数据升级
%%% @end
%%% Created : 08. 7月 2021 16:44
%%%-------------------------------------------------------------------
-module(role_ver).
-author("liuwentao").

%% API
-export([
    do/2
]).

-include("role.hrl").
-include("common.hrl").

%% @doc 角色数据升级函数
do(?role_ver, Role = #role{}) ->
    parse_field([p_bag, p_store, assets], Role);
do(Ver, Data) ->
    ?INFO("Ver:~w, Data:~w", [Ver, Data]),
    ?ERR("角色数据项不匹配, 转换失败"),
    {error, role_data_convert_failure}.



%% @doc 先对role的直接子项进行解释，只有全部正常解释才可以通过
-spec parse_field([Type :: atom()], Data :: #role{}) -> {ok, #role{}} | {error, role_data_convert_failure}.
parse_field([], Role) -> {ok, Role};
parse_field([Field | T], Role) ->
    case parse_field(Field, Role) of
        {error, _Reason} ->
            ?ERR("版本转换失败：~ts", [_Reason]),
            {error, role_data_convert_failure};
        {ok, NewRole} ->
            parse_field(T, NewRole)
    end;
%% 背包升级
parse_field(p_bag, Role = #role{p_bag = PBag}) ->
    case package_ver:do(PBag) of
        {false, Reason} -> {error, Reason};
        {ok, NewPBag} ->
            {ok, Role#role{p_bag = NewPBag}}
    end;
%% 仓库升级
parse_field(p_store, Role = #role{p_store = PBag}) ->
    case package_ver:do(PBag) of
        {false, Reason} -> {error, Reason};
        {ok, NewPBag} ->
            {ok, Role#role{p_store = NewPBag}}
    end;
%% 资产
parse_field(assets, Role = #role{assets = Assets}) ->
    case assets_ver:do(Assets) of
        {false, Reason} -> {error, Reason};
        {ok, NewAssets} ->
            {ok, Role#role{assets = NewAssets}}
    end;
%% 容错
parse_field(Field, _Role) ->
    {error, util:flist(?T("无法识别数据项:~w"), [Field])}.